package com.lam.framework.bean.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.common.components.dict.constant.DictConstant;
import com.lam.common.components.dict.model.TableDictInfo;
import com.lam.common.components.dict.service.TableDictConfigService;
import com.lam.common.components.redis.RedisUtil;
import com.lam.common.constant.CommonConstant;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.StringUtils;
import com.lam.common.utils.sql.SqlUtil;
import com.lam.framework.bean.entity.SysTableDict;
import com.lam.framework.bean.mapper.TableDictMapper;

/**
 * Table字典配置Service业务层处理
 * 
 * @author admin
 * @date 2022-08-01
 */
@Service
public class TableDictServiceImpl implements TableDictConfigService {

    @Autowired
    private TableDictMapper tableDictMapper;
    
    @Override
    @Transactional(readOnly = true)
    public List<String> selectAllTableName(){
    	
    	QueryWrapper<SysTableDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", CommonConstant.STATUS_NORMAL);
        List<SysTableDict> list = tableDictMapper.selectList(queryWrapper);
		return new ArrayList<>(list.stream().map(SysTableDict::getTableName).collect(Collectors.toSet()));
    }
    
    
    @Override
//    @Cacheable(value = SystemConstant.TABLE_DICT_CONFIG + "#1D", key = "#root.args[0]", unless = "#result == null")
    @Transactional(readOnly = true)
	public TableDictInfo selectTableDictConfig(String dictCode) {

    	Object v = RedisUtil.get(DictConstant.TABLE_DICT_CONFIG + dictCode);
    	if(v != null) {
    		return CollectionUtil.cast(v);
    	}

        String[] dictSs = dictCode.split(":");
    	QueryWrapper<SysTableDict> queryWrapper = new QueryWrapper<>();
    	queryWrapper.eq("dict_code", dictSs[0]);
        queryWrapper.eq("status", 1);
        queryWrapper.last(" limit 1");
    	SysTableDict tableDict = tableDictMapper.selectOne(queryWrapper);
    	if(tableDict != null && NumberUtil.eq(tableDict.getStatus(), CommonConstant.STATUS_NORMAL_1) ) {
    		Object[] values = null;
    		if(dictSs.length > 1) {
    			values = StringUtils.split(dictSs[1], ",");
    		}
    		String exeConditionSql = SqlUtil.createSql(tableDict.getConditionSql(), values);
    		TableDictInfo tableDictInfo = new TableDictInfo(tableDict.getTableName(), tableDict.getValueField(), tableDict.getTextField(), tableDict.getConditionSql())
    				.exeConditionSql(exeConditionSql);
    		RedisUtil.set(DictConstant.TABLE_DICT_CONFIG + dictSs[0], tableDictInfo, 60*60*24);
    		return tableDictInfo;
    	}
		return null;
	}


}
